package controllers

import (
	"BeegoFirst/models"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"time"
)

type LoginController struct {
	beego.Controller
}

func (This *LoginController) Get() {

	name := This.Ctx.GetCookie("userName")
	This.Data["name"] = name

	This.TplName = "login.html"
}

func (This *LoginController) Post() {

	name := This.GetString("userName")
	password := This.GetString("password")

	if name == "" || password == "" {
		This.Ctx.WriteString("用户名和密码不可以为空")
		return
	}

	o := orm.NewOrm()
	user := models.User{Username: name}
	err := o.Read(&user, "Username")
	if err != nil {
		This.Ctx.WriteString("用户名不存在")
		return
	}

	if user.Password != password {
		This.Ctx.WriteString("密码错误")
		return
	}

	remember := This.GetString("remember")

	if remember == "on" {
		This.Ctx.SetCookie("userName", name, time.Second*60)
	} else {
		This.Ctx.SetCookie("userName", name, -1)
	}
	This.SetSession("userName", user.Username)

	This.Redirect("/api/index", 302)

}

type RegController struct {
	beego.Controller
}

func (This *RegController) Get() {
	This.TplName = "register.html"
}

func (This *RegController) Post() {
	name := This.GetString("userName")
	password := This.GetString("password")
	if name == "" || password == "" {
		This.Ctx.WriteString("用户名和密码不可以为空")
		return
	}

	o := orm.NewOrm()
	user := models.User{Password: password, Username: name}
	_, err := o.Insert(&user)
	if err != nil {
		This.Ctx.WriteString("添加失败")
		return
	}

	This.Redirect("/login", 302)

}

type LogoutController struct {
	beego.Controller
}

func (This *LogoutController) Get() {
	This.DelSession("userName")
	This.Redirect("/", 302)
}

type GotoController struct {
	beego.Controller
}

func (This *GotoController) Get() {
	This.Redirect("/api/index", 302)
}
